﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
// Krzysztof Heim
// pktools.codeplex.com

namespace PKTools.Database
{
    public class MsSql : Sql
    {
        public MsSql(string connection = null, SqlConnection outerConnection = null)
            : base(connection, outerConnection == null)
        {
            this.command = new SqlCommand(string.Empty, outerConnection ?? new SqlConnection(this.connection));
        }

        public override DbParameter AddInput(string key, object value, Type type = null)
        {
            var
                size = -1;

            if (value == null)
                value = DBNull.Value;
            else
            {
                if (value is string)
                {
                    var
                        n = (value as string).Length;

                    if (n == 0)
                        value = DBNull.Value;
                    else
                    if (n < 32) // set constant size for performance (cache exec. plan)
                        size = 32;
                    if (n < 256)
                        size = 256;
                }
            }

            var
                p = new SqlParameter(key, value);

            if (size != -1)
                p.Size = size;

            this.command.Parameters.Add(p);
            return p;
        }

        public override DbParameter AddOutput(string key, Type type)
        {
            type = GetFinalType(type);

            object
                value = null;
            if (type.IsValueType)
                value = Activator.CreateInstance(type);

            var
                p = new SqlParameter(key, value)
                {
                    Direction = ParameterDirection.Output
                };

            this.command.Parameters.Add(p);
            return p;
        }

        public override decimal GetIdentity()
        {
            Clear();
            var 
                temp = ExecuteScalar("SELECT @@IDENTITY");

            return temp == DBNull.Value ? -1 : (decimal)temp;
        }

        public override string EscapeName(string name)
        {
            return '[' + name + ']';
        }
    }
}
